﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.WCF.Extensions
{
	public class InjectionInstanceProvider : IInstanceProvider
	{
		private IExportStrategy exportStrategy;
		private IDependencyInjectionContainer container;

		public InjectionInstanceProvider(IDependencyInjectionContainer container, Type serviceType)
		{
			this.container = container;

			exportStrategy = container.GetStrategy(serviceType);

			if (exportStrategy == null)
			{
				exportStrategy = new AttributedExportStrategy(new[] { serviceType.FullName }, serviceType);

				exportStrategy.ExportedTypes = new List<Type> { serviceType };

				container.AddStrategy(exportStrategy);
			}
		}

		public object GetInstance(InstanceContext instanceContext)
		{
			return GetInstance(instanceContext, null);
		}

		public object GetInstance(InstanceContext instanceContext, Message message)
		{
			object returnValue = exportStrategy.Activate(container.CreateInjectionContext(), null);

			if (returnValue == null)
			{
				throw new ConfigurationException("Could not create new instance of " + exportStrategy.ExportNames.First());
			}

			return returnValue;
		}

		public void ReleaseInstance(InstanceContext instanceContext, object instance)
		{
		}
	}
}